import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { SongService } from 'src/app/shared';
import { getCurrentSong, getPlayer } from 'src/app/store/selector/play.selector';
import { StoreActionService } from 'src/app/store/store-action.service';
import { AppStoreModule } from 'src/app/store/store.module';
import { Song, SongSheet } from '../entity';

@Component({
  selector: 'app-sheet-detail',
  templateUrl: './sheet-detail.component.html',
  styleUrls: ['./sheet-detail.component.less']
})
export class SheetDetailComponent implements OnInit, OnDestroy {

  sheetDetail: SongSheet;

  sheetDescriptionContent = {
    short: '',
    long: ''
  };

  descControl = {
    isExpand: false,
    label: '展开',
    icon: 'down'
  };

  currentIndex = -1;
  currentSong: Song;

  private listenDestory = new Subject<void>();

  constructor(
    private activatedRoute: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private songService: SongService,
    private storeActionService: StoreActionService,
    private msg: NzMessageService
  ) { }

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ sheetDetail }) => {
      this.sheetDetail = sheetDetail;
      if (this.sheetDetail && this.sheetDetail.description) {
        this.parseDescription(this.sheetDetail.description);
      }
    });
    this.listenCurrentSong();
  }

  ngOnDestroy(): void {
    this.listenDestory.next();
    this.listenDestory.complete();
  }

  shareResource(value: any, a: string = ''): void {

  }

  onLikeSheet(value: any): void {

  }

  onLikeSong(value: any): void {

  }

  toggleDesc(): void {
    this.descControl.isExpand = !this.descControl.isExpand;
    if (this.descControl.isExpand) {
      this.descControl.icon = 'up';
      this.descControl.label = '收起';
    } else {
      this.descControl.icon = 'down';
      this.descControl.label = '展开';
    }
  }

  onAddSongs(songs: Song[], isPlay = false): void {
    this.songService.getSongList(songs)
      .subscribe(list => {
        if (list && list.length > 0) {
          if (isPlay) {
            this.storeActionService.updatePlayList({ list, index: 0 });
          } else {
            this.storeActionService.insertSongs(list);
          }
        }
      });
  }

  onAddSong(song: Song, isPlay = false): void {
    if (this.canAddSong(this.currentSong, song)) {
      this.songService.getSongList(song).subscribe(
        list => {
          if (list && list.length > 0) {
            this.storeActionService.insertSong(list[0], isPlay);
          } else {
            this.msg.warning('无法播放该歌曲');
          }
        }
      );
    }
  }

  private parseDescription(desc: string): void {
    if (!desc) {
      return;
    }
    if (desc.length < 99) {
      this.sheetDescriptionContent.short = '<b>介绍：</b>' + this.replaceBr(desc);
    } else {
      this.sheetDescriptionContent = {
        short: '<b>介绍：</b>' + this.replaceBr(desc.slice(0, 99)) + '...',
        long: '<b>介绍：</b>' + this.replaceBr(desc)
      };
    }
  }

  private replaceBr(value: string): string {
    if (value) {
      return value.replace(/\n/g, '<br/>');
    }
    return '';
  }

  private listenCurrentSong(): void {
    this.store$.pipe(
      select(getPlayer),
      select(getCurrentSong),
      takeUntil(this.listenDestory))
      .subscribe(song => {
        this.currentSong = song;
        if (song) {
          this.currentIndex = this.sheetDetail.tracks.findIndex(e => e.id === song.id);
        } else {
          this.currentIndex = -1;
        }
      });
  }

  private canAddSong(currentSong: Song, addSong: Song): boolean {
    return !currentSong || currentSong.id !== addSong.id;
  }

}
